export const chatIndex = {
	name: 'chatIndex',
	data() {
		return {
			start: 0,
			end: 0,
			source: {},
			isdoctor: false,
		}
	},
	mounted() {
		const client = JSON.parse(sessionStorage.getItem('chatClient'))
		const target = document.getElementById('chatIndex')
		if (client) {
			target.style.left = `${client.left}px`
			target.style.top = `${client.top}px`
		}
	},
	methods: {
		linkToIndex(chatroomId, id) {
			if (this.isdoctor) {
				window.location.href = `https://qywechat.dtx-tech.com/chatroom?client=doctor&userid=${id}&roomid=${chatroomId}`
			} else {
				window.location.href =
					'https://qywechat.dtx-tech.com/chatroom?roomid=' +
					chatroomId +
					'&client=patient' +
					'&userid=' +
					id
			}
		},
		touchStart(e) {
			const ele = e.targetTouches[0]
			const target = document.getElementById('chatIndex')
			this.source.start = {
				left: '',
				top: '',
			}
			this.source.start.left = Number(
				window.getComputedStyle(target).left.replace('px', '')
			)
			this.source.start.top = Number(
				window.getComputedStyle(target).top.replace('px', '')
			)
			this.source.client = {
				x: ele.clientX,
				y: ele.clientY,
			}
			this.start = new Date().getTime()
		},
		touchEnd(e) {
			this.end = new Date().getTime()
			const target = document.getElementById('chatIndex')
			const x = document.body.clientWidth
			const y = document.body.clientHeight
			const width = Number(
				window.getComputedStyle(target).width.replace('px', '')
			)
			let left = Number(window.getComputedStyle(target).left.replace('px', ''))
			let top = Number(window.getComputedStyle(target).top.replace('px', ''))
			if (
				this.source.start.left == left &&
				this.source.start.top == top &&
				this.end - this.start < 300
			) {
				this.linkToIndex()
			} else {
				if (left > x || x - left < width) {
					target.style.left = `${x - width}px`
					left = x - width
				}
				if (top > y || y - top < width) {
					target.style.top = `${y - width}px`
					top = y - width
				}
				if (left < 0) {
					target.style.left = '0px'
					left = 0
				}
				if (top < 0) {
					target.style.top = '0px'
					top = 0
				}
				sessionStorage.setItem('chatClient', JSON.stringify({ left, top }))
			}
		},
		touchMove(e) {
			let element = e.targetTouches[0]
			let left = this.source.start.left + element.clientX - this.source.client.x
			let top = this.source.start.top + element.clientY - this.source.client.y
			const target = document.getElementById('chatIndex')
			target.style.left = `${left}px`
			target.style.top = `${top}px`
		},
	},
	template: `
		<div id="chatIndex" @touchstart="touchStart" @touchend="touchEnd" @touchmove.stop.prevent="touchMove">
			<img src="./img/chat.png"/>
			<p>聊天</p>
		</div>
	`,
}
